package com.three.crm.page.feedback;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.three.crm.R;
import com.three.crm.adapter.FeedbackListAdapter;
import com.three.crm.base.BaseActivity;
import com.three.crm.bean.CommonBean;
import com.three.crm.constant.AppConstant;
import com.three.crm.http.CommonResultCallBack;
import com.three.crm.page.visit.VisitListActivity;
import com.three.crm.require.AppRequireService;
import com.three.crm.util.AppManager;
import com.three.crm.util.GsonUtils;
import com.three.crm.util.SignUtil;
import com.three.crm.util.XpopupUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import okhttp3.Call;

/**
 * 反馈质量
 * created by lqd on 2024-01-05.
 */
public class QualityListActivity extends BaseActivity {

    private EditText etInput;
    private ImageView ivAdd;
    private TextView tvLoading,tvTitle;
    private View mLoadingView;
    private ImageView ivState;
    private ProgressBar progressBar;
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private FeedbackListAdapter adapter;
    private int pageNo = 1;
    private boolean isloadMore = false;
    private String keyWord = "";

    @Override
    protected void initParms(Bundle bundle) {}

    @Override
    protected int bindLayout() {
        return R.layout.common_list_layout;
    }

    @Override
    protected void initViews(View view, Bundle savedInstanceState) {
        AppManager.setNeedUpdate(false);
        tvTitle = $(R.id.tv_title);
        tvTitle.setText(R.string.quality_feedback);
        ivAdd = $(R.id.iv_right);
        ivAdd.setVisibility(View.VISIBLE);

        etInput = $(R.id.et_input);
        refreshLayout = $(R.id.refresh_layout);
        mLoadingView = LayoutInflater.from(this).inflate(R.layout.loading_view,null);
        ivState = mLoadingView.findViewById(R.id.iv_state);
        tvLoading = mLoadingView.findViewById(R.id.tv_loading);
        progressBar = mLoadingView.findViewById(R.id.progressBar);

        recyclerView = $(R.id.recycleview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        adapter = new FeedbackListAdapter();
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void setListener() {
        $(R.id.iv_left).setOnClickListener(this);
        $(R.id.iv_right).setOnClickListener(this);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshing();
            }
        });
        tvLoading.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshing();
            }
        });
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                recyclerView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (isloadMore) {
                            pageNo ++;
                            loadData();
                        }
                    }
                },1000);
            }
        },recyclerView);
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter baseQuickAdapter, @NonNull View view, int position) {
                CommonBean bean = (CommonBean) baseQuickAdapter.getItem(position);
                int id = view.getId();
                switch (id){
                    case R.id.tv_detail:
                        handleClick(bean,"detail");
                        break;
                    case R.id.tv_edit:
                        handleClick(bean,"edit");
                        break;
                }
            }
        });
        etInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                keyWord = s.toString();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshing();
                    }
                },500);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void handleClick(CommonBean bean, String index) {
        if (index.equals("detail")) {
            Bundle bundle = new Bundle();
            bundle.putInt(AppConstant.EXTRAS_DATA,bean.getId());
            startActivity(QualityDetailActivity.class,bundle);
        } else if (index.equals("edit")) {
            int userType = AppManager.getLevel();
            if (userType == 2) {
                Bundle bundle = new Bundle();
                bundle.putParcelable(AppConstant.EXTRAS_DATA,bean);
                startActivity(QualityEditActivity.class,bundle);
            } else {
                XpopupUtil.showTips(this, getString(R.string.You_currently_do_not_have_permission_to_access));
            }
        }
    }

    @Override
    protected void widgetClick(View v) {
        switch (v.getId()){
            case R.id.iv_left:
                finish();
                break;
            case R.id.iv_right:
                int userType = AppManager.getLevel();
                if (userType == 2) {
                    startActivity(QualityEditActivity.class);
                } else {
                    XpopupUtil.showTips(this, getString(R.string.You_currently_do_not_have_permission_to_access));
                }
                break;
        }
    }

    @Override
    protected void initData(Context mContext) {
        refreshing();
    }

    private void refreshing() {
        if (refreshLayout != null && refreshLayout.isRefreshing()) {
            refreshLayout.setRefreshing(true);
        }
        progressBar.setVisibility(View.VISIBLE);
        tvLoading.setText(getString(R.string.loading));
        ivState.setVisibility(View.GONE);
        adapter.setEnableLoadMore(true);
        adapter.getData().clear();
        pageNo = 1;
        isloadMore = false;
        loadData();
    }

    private void loadData() {
        adapter.setEmptyView(mLoadingView);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("userToken", AppManager.getToken());
            jsonObject.put("pageNo",pageNo);
            jsonObject.put("pageSize",AppConstant.PAGE_SIZE);
            jsonObject.put("keyword",keyWord);
            jsonObject.put("timestamp",getTimestamp());
            String sign = SignUtil.genSign(jsonObject);
            jsonObject.put("sign",sign);
            AppRequireService.queryFeedbackList(this, AppConstant.QUERY_LIST, jsonObject, new CommonResultCallBack(this) {
                @Override
                public void onResult(String result, int requireCode) {
                    resetRefresh();
                    Log.i("TAG","result="+result);
                    if (requireCode == AppConstant.QUERY_LIST) {
                        List<CommonBean> tempList = GsonUtils.parseJsonArrayWithGson(result,CommonBean.class);
                        setListAdapter(tempList);//设置页面数据
                    }
                }

                @Override
                public void onConnectTimeOut(Call call, Exception e, int requireCode) {
                    resetRefresh();
                    showToast(e.getMessage());
                    setState(getString(R.string.connect_time_out),R.mipmap.ic_http_error);
                }

                @Override
                public void onFail(String msg, int requireCode) {
                    resetRefresh();
                    showToast(msg);
                    adapter.loadMoreFail();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void setListAdapter(List<CommonBean> mList) {
        resetRefresh();
        if (isloadMore) {
            adapter.addData(mList);
            if (mList.size() < AppConstant.PAGE_SIZE) {
                adapter.loadMoreEnd();
            } else {
                adapter.loadMoreComplete();
                adapter.setEnableLoadMore(true);
            }
        } else if (mList.isEmpty()) {
            adapter.loadMoreEnd();
            adapter.setEnableLoadMore(false);
            setState(getString(R.string.no_data),R.mipmap.ic_empty);
        } else {
            adapter.setNewData(mList);
            adapter.loadMoreComplete();
            adapter.setEnableLoadMore(true);
            isloadMore = true;
        }
    }

    private void setState(String string, int resId) {
        progressBar.setVisibility(View.GONE);
        tvLoading.setText(string);
        ivState.setImageResource(resId);
        ivState.setVisibility(View.VISIBLE);
        adapter.setEmptyView(mLoadingView);
        adapter.notifyDataSetChanged();
    }

    private void resetRefresh() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.setRefreshing(false);
        }
        progressBar.setVisibility(View.GONE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        resetRefresh();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (AppManager.getNeedUpdate()) {
            refreshing();
            AppManager.setNeedUpdate(false);
        }
    }
}